package lmscript.postscript.io;

import java.io.IOException;
import java.io.OutputStream;

public class ASCIIHexOutputStream extends OutputStream {

	private final static int MAX_CHARS_PER_LINE = 80;
	private OutputStream out;
	private int written = 0;

	public ASCIIHexOutputStream(OutputStream out) {
		this.out = out;
	}

	@Override
	public void write(int b) throws IOException {
		String s = Integer.toHexString(b & 0x00FF);
		switch (s.length()) {
		case 1:
			writeChar('0');
			writeChar(s.charAt(0));
			break;
		case 2:
			writeChar(s.charAt(0));
			writeChar(s.charAt(1));
			break;
		default:
			throw new IOException("input hex bytes length error: " + b);
		}
	}

	public void finish() throws IOException {
		writeChar('>');
		out.flush();
	}

	public void close() throws IOException {
		finish();
		out.close();
	}

	private void writeChar(int c) throws IOException {
		if (written >= MAX_CHARS_PER_LINE) {
			this.out.write('\n');
			written = 0;
		}
		written++;
		this.write(c);
	}
}
